<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/28
 * Time: 14:27
 */
namespace app\command\cron;

use app\index\service\ExtendService;
use OSS\OssClient;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class runVoice extends Command{

    protected function configure()
    {
        $this->setName('runVoice')
            ->setDescription('执行转换语音业务任务');
    }


    /**
     * 执行转换语音业务任务
     * @param Input $input
     * @param Output $output
     * @return int|null|void
     * @throws \OSS\Core\OssException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(1720000);
        ini_set('memory_limit','5024M');
        //获取没有语音文件的题目
        $question = Db::name('question')
            ->select()->toArray();
        $service = new ExtendService();
        $temp = [
            '1'=>'A',
            '2'=>'B',
            '3'=>'C',
            '4'=>'D',
            '5'=>'E',
            '6'=>'F',
            '7'=>'G',
            '8'=>'H',
            '9'=>'I',
            '10'=>'J',
        ];
        foreach ($question as $k=>$v){
            sleep(1);
            $token = cache('voiceToken');
            if(empty($token)){
                $token_object = $service->getalyuntoken(config('system.ali')['accessKeyId'],config('system.ali')['accessKeySecret']);
                $token = $token_object['Token']['Id'];
                cache('voiceToken',$token,1*60);
            }
            //获取语音文件
            if($v['type_'] == '1'){
                $question_type = '判断题';
                $output->writeln('题目的id：'.$v['id_']);
                if($v['answer_true'] == '1'){
                    $answer = '正确';
                }else{
                    $answer = '错误';
                }
                $text = "{$question_type}，{$v['question_']}。答案是：{$answer}";
            }elseif ($v['type_'] == '2'){
                $question_type = '单选题';
                $output->writeln('题目的id：'.$v['id_']);
                $answer = $temp[$v['answer_true']];
                $xuanxiang = '';
                if(!empty($v['an1_'])){
                    $xuanxiang = $xuanxiang.'A '.$v['an1_'].'。';
                }
                if(!empty($v['an2_'])){
                    $xuanxiang = $xuanxiang.'B '.$v['an2_'].'。';
                }
                if(!empty($v['an3_'])){
                    $xuanxiang = $xuanxiang.'C '.$v['an3_'].'。';
                }
                if(!empty($v['an4_'])){
                    $xuanxiang = $xuanxiang.'D '.$v['an4_'].'。';
                }
                if(!empty($v['an5_'])){
                    $xuanxiang = $xuanxiang.'E '.$v['an5_'].'。';
                }
                if(!empty($v['an6_'])){
                    $xuanxiang = $xuanxiang.'F '.$v['an6_'].'。';
                }
                if(!empty($v['an7_'])){
                    $xuanxiang = $xuanxiang.'G '.$v['an7_'].'。';
                }
                if(!empty($v['an8_'])){
                    $xuanxiang = $xuanxiang.'H '.$v['an8_'].'。';
                }
                if(!empty($v['an9_'])){
                    $xuanxiang = $xuanxiang.'I '.$v['an9_'].'。';
                }
                if(!empty($v['an10_'])){
                    $xuanxiang = $xuanxiang.'J '.$v['an10_'].'。';
                }
                $text = "{$question_type}，{$v['question_']}。{$xuanxiang}答案是：{$answer}。";
            }else{
                $answer = '';
                $question_type = '多选题';
                $output->writeln('题目的id：'.$v['id_']);
                $aa = str_split($v['answer_true']);
                foreach ($aa as $kk=>$vv){
                    $answer = $answer . $temp[$vv];
                }
                $xuanxiang = '';
                if(!empty($v['an1_'])){
                    $xuanxiang = $xuanxiang.'A '.$v['an1_'].'。';
                }
                if(!empty($v['an2_'])){
                    $xuanxiang = $xuanxiang.'B '.$v['an2_'].'。';
                }
                if(!empty($v['an3_'])){
                    $xuanxiang = $xuanxiang.'C '.$v['an3_'].'。';
                }
                if(!empty($v['an4_'])){
                    $xuanxiang = $xuanxiang.'D '.$v['an4_'].'。';
                }
                if(!empty($v['an5_'])){
                    $xuanxiang = $xuanxiang.'E '.$v['an5_'].'。';
                }
                if(!empty($v['an6_'])){
                    $xuanxiang = $xuanxiang.'F '.$v['an6_'].'。';
                }
                if(!empty($v['an7_'])){
                    $xuanxiang = $xuanxiang.'G '.$v['an7_'].'。';
                }
                if(!empty($v['an8_'])){
                    $xuanxiang = $xuanxiang.'H '.$v['an8_'].'。';
                }
                if(!empty($v['an9_'])){
                    $xuanxiang = $xuanxiang.'I '.$v['an9_'].'。';
                }
                if(!empty($v['an10_'])){
                    $xuanxiang = $xuanxiang.'J '.$v['an10_'].'。';
                }
                $text = "{$question_type}，{$v['question_']}。{$xuanxiang}答案是：{$answer}。";
            }
            $text = urlencode($text);
            $appkey=config('system.ali')['aliVoiceKey'];
            $url="https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey={$appkey}&token={$token}&text={$text}&format=mp3&voice=aijia";
            $stream_data = http_get($url);
            $url = app()->getRootPath().'/public/voice/'.createNo().'.mp3';
            file_put_contents($url, $stream_data, true); // 保存文件
            $ossClient = new OssClient(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret'], config('system.ali')['endpoint']);
            $bucket = config('system.ali')['bucket'];
            $object = 'voice/'.createNo().'.mp3';
            $filePath = $url;
            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            $voice_file = $result['info']['url'];
            $voice_file = str_replace('http','https',$voice_file);
            //更新数据
            Db::name('question')
                ->where('id_',$v['id_'])
                ->update(['voice_file'=>$voice_file]);
            $k = $k+1;
            $output->writeln("（题库）第{$k}题语音文件更新已完成");
        }
        $output->writeln("题库全部更新已完成");



        //更新技巧解析语音文件
        $skill = Db::name('skill_chapter_question')
            ->select()->toArray();
        $service = new ExtendService();
        foreach ($skill as $k=>$v){
            sleep(1);
            $token = cache('voiceToken');
            if(empty($token)){
                $token_object = $service->getalyuntoken(config('system.ali')['accessKeyId'],config('system.ali')['accessKeySecret']);
                $token = $token_object['Token']['Id'];
                cache('voiceToken',$token,1*60);
            }
            $text = "{$v['content_']}，{$v['skill_desc']}。";
            $text = urlencode($text);
            $appkey=config('system.ali')['aliVoiceKey'];
            $url="https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey={$appkey}&token={$token}&text={$text}&format=mp3&voice=aijia";
            $stream_data = http_get($url);
            $url = app()->getRootPath().'/public/voice/'.createNo().'.mp3';
            file_put_contents($url, $stream_data, true); // 保存文件
            $ossClient = new OssClient(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret'], config('system.ali')['endpoint']);
            $bucket = config('system.ali')['bucket'];
            $object = 'voice/'.createNo().'.mp3';
            $filePath = $url;
            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            $voice_file = $result['info']['url'];
            $voice_file = str_replace('http','https',$voice_file);
            Db::name('skill_chapter_question')
                ->where('id_',$v['id_'])
                ->update(['voice_file'=>$voice_file]);
            $output->writeln("（技巧题库）题目id：".$v['id_']);
            $output->writeln("（技巧题库）第{$k}题语音文件更新已完成");
        }
        $output->writeln("技巧题库语音更新完成");
        $output->writeln("全部计划任务执行完成");
    }
}